$(document).ready(function(){
	
    var htmlClustersLoading = '<div class="loading"><p><img src="../img/ajax-loader.gif"/> Loading clusters, please wait</p></div>';
    var htmlUsersLoading = '<div class="loading"><p><img src="../img/ajax-loader.gif"/> Calculating neighbors. It can take a few seconds, please wait</p></div>';
    var htmlItemsLoading = '<div class="loading"><p><img src="../img/ajax-loader.gif"/> Loading items list, please wait</p></div>';
 
    initPersonalizedRecommendationsPage();
    
    loadedUsersIdList = new Array();
    loadedTopicsIdList = new Array();    
    loadedItemsIdList = new Array();    
    
    function initPersonalizedRecommendationsPage(){
    	
        showRecommendedTopics();
        showRecommendedNeighbors();
    }
    
    function showRecommendedNeighbors(){
        $("div#recPersUsers").removeClass("ocult");
        $("div#contingutRecPersUsers").html(htmlUsersLoading);


        /**
         * show neighbors (users sharing interests) of user connected
         */
        $.ajax({
            url:  "/irssrecommendations/Recommendations/GetNeighbors",
            cache: false,
            dataType: "json",
            success: function(data){
                var recOfUsers = data.userRecommendedList;
                var usrsLstAlreadyShowed = new Array();

                $("div#contingutRecPersUsers").html("");
                
                for (var i=0;i<recOfUsers.length;i++){
                	
                    $("div#contingutRecPersUsers").append('<div class="recPersUser"><div class="persInfo">'+
                        '<div class="userName">'+ recOfUsers[i].name+'</div>'+
                        '<span class="subscribePersUser" title="subscribe it!" value=" '+ recOfUsers[i].login + ' ">'+
                        '<img src="../img/likeit.gif"/></span>'+
                        '<div class="userEmail">'+ recOfUsers[i].email+'</div></div>'+
                        '<div id="persPicture" style="float:right;">'+
                        '<img style="margin:2px;height:76px;width:76px;cursor:pointer;" title="'+ recOfUsers[i].name+'" id="'+ recOfUsers[i].idusuari +'" value="'+recOfUsers[i].login+'" src="../img/users/'+recOfUsers[i].login+'.png">'+
                        '</div></div>');
                        
                    usrsLstAlreadyShowed[i] = recOfUsers[i].idusuari;

                    $("#"+recOfUsers[i].idusuari).click(function(){
                        $(".recPersUser").css('background-color','white');
                        $(this).parent().parent().css('background-color','#E8D0A9');
                        var userId = $(this).attr("id");
                        var userName = $(this).attr("value");
                        $("#recPersClusters").find(".titol").html("<span>Topics you share with "+userName+"</span><div id='showUnfilteredTopics' style='cursor: pointer; font-size: 0.9em; float: right; margin-right: 5px;s'><span>Show unfiltered</span></div>");
                        $("#showUnfilteredTopics").click(function(){
                            showRecommendedTopics();
                        });
                        
                        $("div#contingutRecPersClusters").html(htmlClustersLoading);

                        $.ajax({
                            url:  "/irssrecommendations/Recommendations/GetMatchingClusters?usuari="+userName,
                            cache: false,
                            dataType: "json",
                            success: function(data){                                    
                                var recOfTopics = data.matchingClustersList;
                	            	
                                var topicsLstAlreadyShowed = new Array();
                	            	
                                $("div#contingutRecPersClusters").html("");

                                for (var j=0;j<recOfTopics.length;j++){

                                    $("div#contingutRecPersClusters").append("<div class='persRecTopic'><div title='Show items' class='topicLabel' id='"+recOfTopics[j].idConcept+"' value='"+recOfTopics[j].idConcept+"' >" + recOfTopics[j].valueConcept  + "</div><span class='subscribePersTopic' title='subscribe it!'  value='" + recOfTopics[j].idConcept + "'><img src='../img/likeit.gif'></span></div>");
                                    topicsLstAlreadyShowed[j] = recOfTopics[j].idConcept;

                                    $("#"+recOfTopics[j].idConcept).click(function(){
                                        $(".persRecTopic").css({
                                            "background-color":"#FFFFFF", 
                                            "color":"saddleBrown", 
                                            "border-radius":"0px"
                                        });
                                        $(this).parent().css({
                                            "background-color":"#E8D0A9", 
                                            "border-radius":"6px"
                                        });

                                        listRecommendedItems($(this).attr("id"), $(this).html(), userId);
                               		
                                    });
                                }
                                $("div#contingutRecPersClusters").append("<span id='showMoreTopics' class='persRecTopic'>Show more topics...</span>");
                                $("#showMoreTopics").one("click", function(){

                                    $.ajax({
                                        url:  "/irssrecommendations/Recommendations/FillMatchingClusters?usuari="+userName+"&topicsIdAlreadyShowed="+topicsLstAlreadyShowed,
                                        cache: false,
                                        dataType: "json",
                                        success: function(data){                                    
                                            var recOfTopics = data.fillMatchingClustersList;

                                            if (recOfTopics.length>0) {
                                                $("#showMoreTopics").hide();

                                                for (var j=0;j<recOfTopics.length;j++){

                                                    $("div#contingutRecPersClusters").append("<div class='persRecTopic'><div title='Show items' class='topicLabel' id='"+recOfTopics[j].idConcept+"' value='"+recOfTopics[j].idConcept+"' >" + recOfTopics[j].valueConcept  + "</div><span class='subscribePersTopic' title='subscribe it!'  value='" + recOfTopics[j].idConcept + "'><img src='../img/likeit.gif'></span></div>");

                                                    $("#"+recOfTopics[j].idConcept).click(function(){
                                                        $(".persRecTopic").css({
                                                            "background-color":"#FFFFFF",
                                                            "color":"saddleBrown",
                                                            "border-radius":"0px"
                                                        });
                                                        $(this).parent().css({
                                                            "background-color":"#E8D0A9",
                                                            "border-radius":"6px"
                                                        });
                                                        listRecommendedItems($(this).attr("id"), $(this).html(), userId);

                                                    });


                                                }

                                                $(".persRecTopic").bind("mouseover",function(){

                                                    $(this).find(".subscribePersTopic").show();

                                                    $(".persRecTopic").bind("mouseout",function(){
                                                        $(this).find(".subscribePersTopic").hide();
                                                    });
                                                });

                                                $(".subscribePersTopic").click(function(){
                                                    if(confirm("You are going to subscribe this topic. Dou you want to continue?")) {
                                                        var topicId = $(this).attr("value");
                                                        $('body').css('cursor', 'wait');

                                                        $.ajax({
                                                            url:  "/irssrecommendations/Recommendations/CreateTopicSubscription?selectedConceptId="+topicId,
                                                            cache: false,
                                                            dataType: "json",
                                                            success: function(){
                                                                if (data.errorMessage!=null && data.errorMessage!="") {
                                                                    alert(data.errorMessage);
                                                                } else {
                                                                    alert("Success! Topic subscribed. You can browse it in the RSS Reader view.");
                                                                }
                                                                $('body').css('cursor', 'auto');

                                                            }
                                                        });

                                                    }

                                                });
                                            }
                                            else {
                                                $("#showMoreTopics").html("there are no more topics.");
                                            }
                                            
                                        }
                                    });
                                });

                                $(".persRecTopic").bind("mouseover",function(){
                                    
                                    $(this).find(".subscribePersTopic").show();
                                    
                                    $(".persRecTopic").bind("mouseout",function(){
                                        $(this).find(".subscribePersTopic").hide();                                    
                                    });
                                });
                                                  
                                $(".subscribePersTopic").click(function(){
                                    if(confirm("You are going to subscribe this topic. Dou you want to continue?")) {
                                        var topicId = $(this).attr("value");
                                        $('body').css('cursor', 'wait');

                                        $.ajax({
                                            url:  "/irssrecommendations/Recommendations/CreateTopicSubscription?selectedConceptId="+topicId,
                                            cache: false,
                                            dataType: "json",
                                            success: function(){

                                                if (data.errorMessage!=null && data.errorMessage!="") {
                                                    alert(data.errorMessage);
                                                } else {
                                                    alert("Success! Topic subscribed. You can browse it in the RSS Reader view.");
                                                }
                                                $('body').css('cursor', 'auto');

                                            }
                                        });

                                    }
                               		
                                });
                            }
                        });
                        
                    });

                }

                $("div#contingutRecPersUsers").append("<div id='showMoreUsers'>Show more neighbors...</div>");

                $("#showMoreUsers").one("click", function(){

                    $.ajax({
                        url: "/irssrecommendations/Recommendations/FillNeighbors?usersIdAlreadyShowed="+usrsLstAlreadyShowed,
                        cache: false,
                        dataType: "json",
                        success: function(data){
                            var fillOfUsers = data.fillUserRecommendedList;
                            if (fillOfUsers.length>0){
                                $("#showMoreUsers").append("<span> Showing other " + fillOfUsers.length + " neighbors</span>")
                                for (var i=0;i<fillOfUsers.length;i++){

                                    $("div#contingutRecPersUsers").append('<div class="recPersUser"><div class="persInfo">'+
                                        '<div class="userName">'+ fillOfUsers[i].name+'</div>'+
                                        '<span class="subscribePersUser" title="subscribe it!" value=" '+ fillOfUsers[i].login + ' ">'+
                                        '<img src="../img/likeit.gif"/></span>'+
                                        '<div class="userEmail">'+ fillOfUsers[i].email+'</div></div>'+
                                        '<div id="persPicture" style="float:right;">'+
                                        '<img style="margin:2px;height:76px;width:76px;cursor:pointer;" title="'+ fillOfUsers[i].name+'" id="'+ fillOfUsers[i].idusuari +'" value="'+fillOfUsers[i].login+'" src="../img/users/'+fillOfUsers[i].login+'.png">'+
                                        '</div></div>');
                                    $("#"+fillOfUsers[i].idusuari).click(function(){
                                        $(".recPersUser").css('background-color','white');
                                        $(this).parent().parent().css('background-color','#E8D0A9');
                                        var userId = $(this).attr("id");
                                        var userName = $(this).attr("value");

                                        $("div#contingutRecPersClusters").html(htmlClustersLoading);

                                        $.ajax({
                                            url:  "/irssrecommendations/Recommendations/GetMatchingClusters?usuari="+userName,
                                            cache: false,
                                            dataType: "json",
                                            success: function(data){
                                                var recOfTopics = data.matchingClustersList;

                                                //recOfTopcis[][0] --> concepte
                                                //recOfTopcis[][1] --> etiqueta

                                                $("div#contingutRecPersClusters").html("");

                                                for (var j=0;j<recOfTopics.length;j++){

                                                    $("div#contingutRecPersClusters").append("<div class='persRecTopic'><div title='Show items' class='topicLabel' id='"+recOfTopics[j].idConcept+"' value='"+recOfTopics[j].idConcept+"' >" + recOfTopics[j].valueConcept  + "</div><span class='subscribePersTopic' title='subscribe it!'  value='" + recOfTopics[j].idConcept + "'><img src='../img/likeit.gif'></span></div>");

                                                    $("#"+recOfTopics[j].idConcept).click(function(){
                                                        $(".persRecTopic").css({
                                                            "background-color":"#FFFFFF",
                                                            "color":"saddleBrown",
                                                            "border-radius":"0px"
                                                        });
                                                        $(this).parent().css({
                                                            "background-color":"#E8D0A9",
                                                            "border-radius":"6px"
                                                        });
                                                        listRecommendedItems($(this).attr("id"), $(this).html(), userId);

                                                    });


                                                }

                                                $(".persRecTopic").bind("mouseover",function(){

                                                    $(this).find(".subscribePersTopic").show();

                                                    $(".persRecTopic").bind("mouseout",function(){
                                                        $(this).find(".subscribePersTopic").hide();
                                                    });
                                                });

                                                $(".subscribePersTopic").click(function(){
                                                    if(confirm("You are going to subscribe this topic. Dou you want to continue?")) {
                                                        var topicId = $(this).attr("value");
                                                        $('body').css('cursor', 'wait');

                                                        $.ajax({
                                                            url:  "/irssrecommendations/Recommendations/CreateTopicSubscription?selectedConceptId="+topicId,
                                                            cache: false,
                                                            dataType: "json",
                                                            success: function(){

                                                                if (data.errorMessage!=null && data.errorMessage!="") {
                                                                    alert(data.errorMessage);
                                                                } else {
                                                                    alert("Success! Topic subscribed. You can browse it in the RSS Reader view.");
                                                                }
                                                                $('body').css('cursor', 'auto');

                                                            }
                                                        });

                                                    }

                                                });
                                            }
                                        });

                                    });
                                }
                                $(".recPersUser").bind("mouseover",function() {

                                    $(this).find(".subscribePersUser").show();

                                    $(".recPersUser").bind("mouseout",function(){
                                        $(this).find(".subscribePersUser").hide();
                                    });
                                });

                                $(".subscribePersUser").bind("click", function(){
                                    if(confirm("You are going to subscribe to this user. Dou you want to continue?")){
                                        var userLogin = $(this).attr("value");
                                        $('body').css('cursor', 'wait');

                                        $.ajax({
                                            url:  "/irssrecommendations/Recommendations/CreateUserSubscription?usuari="+userLogin,
                                            cache: false,
                                            dataType: "json",
                                            success: function(){
                                        
                                                if (data.errorMessage!=null && data.errorMessage!="") {
                                                    alert(data.errorMessage);
                                                } else {
                                                    alert("Success! You are following the user from now on. You can browse it in the RSS Reader view.")
                                                }
                                                $('body').css('cursor', 'auto');

                                            }
                                        });

                                    }
                                });
                                $("div#contingutRecPersUsers").scrollTo($("#showMoreUsers"),800);

                            } else {
                                $("#showMoreUsers").append("<span>You don't have more neighbors.</span>");
                            }

                        }
                    });
                });

                $(".recPersUser").bind("mouseover",function() {
                                    
                    $(this).find(".subscribePersUser").show();
                                    
                    $(".recPersUser").bind("mouseout",function(){
                        $(this).find(".subscribePersUser").hide();                                    
                    });
                });
                                     
                $(".subscribePersUser").bind("click", function(){
                    if(confirm("You are going to subscribe to this user. Dou you want to continue?")){
                        var userLogin = $(this).attr("value");
                        $('body').css('cursor', 'wait');

                        $.ajax({
                            url:  "/irssrecommendations/Recommendations/CreateUserSubscription?usuari="+userLogin,
                            cache: false,
                            dataType: "json",
                            success: function(){
                                if (data.errorMessage!=null && data.errorMessage!="") {
                                    alert(data.errorMessage);
                                } else {
                                    alert("Success! You are following the user from now on. You can browse it in the RSS Reader view.")
                                }
                                $('body').css('cursor', 'auto');

                            }
                        });

                    }
                });

            }
        });
    }
    
    function showRecommendedTopics() {
        $("#recPersClusters").find(".titol").html("<span>Topics you might like</span>");
        $("div#contingutRecPersClusters").html(htmlClustersLoading);

        $.ajax({
            url:  "/irssrecommendations/Recommendations/GetClusters",
            cache: false,
            dataType: "json",
            success: function(data){
                var recOfTopics = data.matchingClustersList;

                var topicsMainLstAlreadyShowed = new Array();

                $("div#contingutRecPersClusters").html("");

                for (var j=0;j<recOfTopics.length;j++){

                    $("div#contingutRecPersClusters").append("<div class='persRecTopic'><div title='Show items' class='topicLabel' id='"+recOfTopics[j].idConcept+"' value='"+recOfTopics[j].idConcept+"' userId = '" + recOfTopics[j].idUser + "'>" + recOfTopics[j].valueConcept  + "</div><span class='subscribePersTopic' title='subscribe it!'  value='" + recOfTopics[j].idConcept + "'><img src='../img/likeit.gif'></span></div>");
                    topicsMainLstAlreadyShowed[j] = recOfTopics[j].idConcept;
                    

                    $("#"+recOfTopics[j].idConcept).click(function(){
                        $(".persRecTopic").css({
                            "background-color":"#FFFFFF",
                            "color":"saddleBrown",
                            "border-radius":"0px"
                        });
                        $(this).parent().css({
                            "background-color":"#E8D0A9",
                            "border-radius":"6px"
                        });

                        listRecommendedItems($(this).attr("id"), $(this).html(), $(this).attr("userId"));

                    });
                }
                $("div#contingutRecPersClusters").append("<span id='showMoreTopics' class='persRecTopic'>Show more topics...</span>");

                $("#showMoreTopics").one("click", function(){
                    $.ajax({
                        url:  "/irssrecommendations/Recommendations/FillClusters?topicsIdAlreadyShowed="+topicsMainLstAlreadyShowed,
                        cache: false,
                        dataType: "json",
                        success: function(data){
                            var recOfTopics = data.fillMatchingClustersList;

                            if (recOfTopics.length>0) {
                                $("#showMoreTopics").hide();

                                for (var j=0;j<recOfTopics.length;j++){

                                    $("div#contingutRecPersClusters").append("<div class='persRecTopic'><div title='Show items' class='topicLabel' id='"+recOfTopics[j].idConcept+"' value='"+recOfTopics[j].idConcept+"' >" + recOfTopics[j].valueConcept  + "</div><span class='subscribePersTopic' title='subscribe it!'  value='" + recOfTopics[j].idConcept + "'><img src='../img/likeit.gif'></span></div>");

                                    $("#"+recOfTopics[j].idConcept).click(function(){
                                        $(".persRecTopic").css({
                                            "background-color":"#FFFFFF",
                                            "color":"saddleBrown",
                                            "border-radius":"0px"
                                        });
                                        $(this).parent().css({
                                            "background-color":"#E8D0A9",
                                            "border-radius":"6px"
                                        });
                                        listRecommendedItems($(this).attr("id"), $(this).html(), userId);

                                    });


                                }

                                $(".persRecTopic").bind("mouseover",function(){

                                    $(this).find(".subscribePersTopic").show();

                                    $(".persRecTopic").bind("mouseout",function(){
                                        $(this).find(".subscribePersTopic").hide();
                                    });
                                });

                                $(".subscribePersTopic").click(function(){
                                    if(confirm("You are going to subscribe this topic. Dou you want to continue?")) {
                                        var topicId = $(this).attr("value");
                                        $('body').css('cursor', 'wait');

                                        $.ajax({
                                            url:  "/irssrecommendations/Recommendations/CreateTopicSubscription?selectedConceptId="+topicId,
                                            cache: false,
                                            dataType: "json",
                                            success: function(){

                                                if (data.errorMessage!=null && data.errorMessage!="") {
                                                    alert(data.errorMessage);
                                                } else {
                                                    alert("Success! Topic subscribed. You can browse it in the RSS Reader view.");
                                                }
                                                $('body').css('cursor', 'auto');

                                            }
                                        });

                                    }

                                });
                            }
                            else {
                                $("#showMoreTopics").html("there are no more topics.");
                            }

                        }
                    });
                });

                $(".persRecTopic").bind("mouseover",function(){

                    $(this).find(".subscribePersTopic").show();

                    $(".persRecTopic").bind("mouseout",function(){
                        $(this).find(".subscribePersTopic").hide();
                    });
                });

                $(".subscribePersTopic").click(function(){
                    if(confirm("You are going to subscribe this topic. Dou you want to continue?")) {
                        var topicId = $(this).attr("value");
                        $('body').css('cursor', 'wait');

                        $.ajax({
                            url:  "/irssrecommendations/Recommendations/CreateTopicSubscription?selectedConceptId="+topicId,
                            cache: false,
                            dataType: "json",
                            success: function(){

                                if (data.errorMessage!=null && data.errorMessage!="") {
                                    alert(data.errorMessage);
                                } else {
                                    alert("Success! Topic subscribed. You can browse it in the RSS Reader view.");
                                }
                                $('body').css('cursor', 'auto');

                            }
                        });

                    }

                });
            }
        });
    }

    /*
     * Llistat de les lectures 
     * d'una subscripcio
     * a la zona de llista de lectures
     */
    function listRecommendedItems(conceptId, conceptName, userId){
		
        $("#textMain").hide();
        $("#llistaItemsSubscripcio").html(htmlItemsLoading);
        $("#llistaItemsSubscripcio").show();

        $.ajax({
            url: "/irssrecommendations/Recommendations/GetPersItemsByCluster?selectedConceptId="+conceptId+"&selectedUserId="+userId,
            cache: true,
            dataType: "json",
            success: function(data){
                var items = data.persItemsList;
                loadedItemsIdList = new Array(items.length);
                //Amaguem el contenidor d'items si es que hi ha alguna cosa
                $("#llistaItemsSubscripcio").html("Showing " + items.length + " elements talking about " + conceptName);

                for (var idx=0;idx<items.length;idx++){
                    $("#textMain").hide();
                    var item = items[idx]
       
                    $("#llistaItemsSubscripcio").append("<div id='" + item.id + "' class='contenidorItem'>"+
                        "<h2 id='titolContingutItem'>"+
                        "<a href='"+item.link+"' target='_blank'>"+item.title+"</a>"+
                        "</h2>"+
                        "<div class='subheaderItem'>"+
                        "<div class='publishedDateItem'>Published data: "+item.dataPublicacioString+"</div>"+
                        //TODO arreglar el feed que aparegui millor
                        "<div class='readedIn'>readed in " + item.feed.titol + "<span class='subscribePersFeed' title='" + item.feed.titol + "'  value='" + item.feed.link + "'><img src='../img/likeit.gif'/></span></div>"+
                        "</div>"+
                        "<div class='itemContent'>"+ item.content +"</div>"+
                        "</div>");
                                              	            		
                    //save items already showed 
                    loadedItemsIdList[idx] = item.id;
                }
                //un cop plena, la mostrem
                $("#llistaItemsSubscripcio").show();
                $("#llistaItemsSubscripcio").append("<div>You've seen all items talking about "+ conceptName +".</div>");
                
                
                $(".subscribePersFeed").bind("click", function(){

                    $("#urlFeed").val($(this).attr('value'));
                                        
                    $(this).colorbox({
                        width: '360px',
                        height:'200px',
                        inline:true,
                        open:true,
                        href:"#addSubscriptionFromRecommendation"
                    });

                });
            }
        });
    }   
    
    $("#centreRecomanacions img").click(function(){
        if($("#esquerraRecomanacions").is(":hidden"))
        {
            $("#esquerraRecomanacions").show('slow');
            $("#dretaRecomanacions").css("width",'70%');

        } else {
            $("#esquerraRecomanacions").hide('slow');
            $("#dretaRecomanacions").css("width",'99%');
        }
    });
   
    //Metode per amagar i mostrar la cap?alera de la aplicacio
    $("#minimitzarCapcalera").click(function(){
		 
        var x = $("#recommendationsMainContent").height();
        var y = $("#header").height();

        if($("#header").is(":hidden"))
        {
            $("#header").slideDown("slow");
            $("#recommendationsMainContent").css("height",x-y);
            $("#minimitzarCapcalera").html("Hide header");

        }
        else
        {
            $("#header").slideUp("slow");
            $("#recommendationsMainContent").css("height",x+y);
            $("#minimitzarCapcalera").html("Show header");

        }
	 
    }); 
    
    $(document).bind('cbox_closed', function(){
	 
        if ($("#textLoadingAfegirSubscripcio").html()!="") {
            $("input#urlFeedAfegir").val("");
            $("input#urlFeedEsborrar").val("");
            $("input#formEtiqueta").val("");
            $("input#urlFeed").val("");
            $("input#labelFeed").val("");
            $("#textLoadingAfegirSubscripcio").html("");
            $("#textLoadingEliminarSubscripcio").html("");
        }
	 
    });
    
    
    $("#btnAddRecommendedSubscription").bind("click", function(){
        
        var form = $("#formAddSubscriptionFromRecommendation");
        if(confirm("You are going to subscribe this feed. Dou you want to continue?")) {
                            
            var url = form.find("#urlFeed").val();
            var label = form.find("#labelFeed").val();
            $('body').css('cursor', 'wait');

            $.ajax({
                url: "/irssrecommendations/Lector/AddNewSubscription?urlFeed="+url+"&etiqueta="+label,
                cache: false,
                dataType: "json",
                success: function(data){
                    if (data.errorMessage!=null && data.errorMessage!="") {
                        alert(data.errorMessage);
                    } else {
                        parent.$.fn.colorbox.close();
                        alert("Subscription added. You can browse it in the reader.");
                    }
                    $('body').css('cursor', 'auto');

                }
            });
        }

    });
    
    $("#formAddSubscriptionFromRecommendation").submit(function() {
        return false;
    });
});